package fun.wxy.camera.entity;

import android.annotation.SuppressLint;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

import fun.wxy.camera.R;

public class UsbDeviceAdapter extends RecyclerView.Adapter<UsbDeviceAdapter.ViewHolder> {

    private final UsbManager usbManager;
    private List<UsbDeviceItem> devices;
    private OnItemClickListener listener;

    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    public UsbDeviceAdapter(UsbManager usbManager, List<UsbDeviceItem> devices) {
        this.usbManager = usbManager;
        this.devices = new ArrayList<>(devices);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_usb_device, parent, false);
        return new ViewHolder(view);
    }

    @Override
    @SuppressLint("DefaultLocale")
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        UsbDeviceItem item = devices.get(position);
        UsbDevice device = item.getDevice();

        // 设置设备信息
        holder.title.setText(item.getTitle());
        holder.ids.setText(String.format("VID: %d  PID: %d", item.getVid(), item.getPid()));

        // 显示权限状态
        boolean hasPermission = usbManager.hasPermission(device);
        holder.status.setText(hasPermission ? "已授权" : "未授权");
        holder.status.setTextColor(hasPermission ?
                holder.itemView.getContext().getColor(android.R.color.holo_green_dark) :
                holder.itemView.getContext().getColor(android.R.color.holo_red_dark));

        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onItemClick(position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return devices.size();
    }

    public void updateList(List<UsbDeviceItem> newList) {
        devices = new ArrayList<>(newList);
        notifyDataSetChanged();
    }

    public UsbDeviceItem getItem(int position) {
        return devices.get(position);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView title;
        TextView ids;
        TextView status;

        ViewHolder(View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.device_title);
            ids = itemView.findViewById(R.id.device_ids);
            status = itemView.findViewById(R.id.device_status);
        }
    }
}